<template>
  <el-row>
    <el-col :span="14" class="col-container">
      用户名：<el-input v-model="selectUsername" placeholder="请输入用户名" style="width: 200px;margin-right: 10px;" />
      <el-button type="primary" @click="selectInfosByWhere"><el-icon><Search /></el-icon>查询</el-button>
    </el-col>
    <el-col :span="8" class="col-container">
      <el-button type="primary" @click="openDialog"><el-icon><Plus /></el-icon>添加用户</el-button>
    </el-col>
    <el-col :span="2"></el-col>
  </el-row>

  <el-table :data="userList" stripe border>
    <el-table-column prop="name" label="用户名" width="150" />
    <el-table-column prop="pass" label="密码" width="150">
      <template #default="{ row }">
        {{ row.pass.replace(/./g, '*') }}
      </template>
    </el-table-column>
    <el-table-column prop="tel" label="电话" width="150" />
    <el-table-column prop="beizhu" label="备注" />
    <el-table-column label="操作" width="200">
      <template #default="{ row }">
        <el-button
          type="primary"
          size="small"
          @click="openModifyDialog(row)"
        >
          <el-icon><Edit /></el-icon>编辑
        </el-button>

        <el-button
          type="danger"
          size="small"
          @click="handleDelete(row.id)"
        >
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加用户对话框 -->
  <el-dialog v-model="dialogVisible" :title="title" width="500px">
    <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleOp">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '@/utils/request.js'

// 用户列表
const userList = reactive([])

// 表单数据
const form = reactive({
  username: '',
  password: '',
  phone: '',
  remark: '',
  id: ''
})

// 表单验证规则
const rules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '长度在6到18个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
})

const dialogVisible = ref(false)
const formRef = ref(null)
const selectUsername = ref('')
const title = ref('新增用户')
const key = ref(false)

// 打开添加用户对话框
const openDialog = () => {
  key.value = false
  title.value = '新增用户'
  dialogVisible.value = true
  Object.keys(form).forEach(key => form[key] = '')
}

// 打开修改用户对话框
const openModifyDialog = (row) => {
  key.value = true
  title.value = '修改用户'
  dialogVisible.value = true
  form.username = row.name || ''
  form.password = row.pass || ''
  form.phone = row.tel || ''
  form.remark = row.beizhu || ''
  form.id = row.id || ''
}

// 处理确认按钮
const handleOp = async () => {
  try {
    await formRef.value.validate()
    if (key.value) {
      await handleModify()
    } else {
      await handleAdd()
    }
  } catch (e) {
    console.log('表单验证失败')
  }
}

// 修改用户信息
const handleModify = () => {
  return new Promise((resolve, reject) => {
    axios.post('/user/modifyInfo.do', {
      name: form.username,
      pass: form.password,
      tel: form.phone,
      beizhu: form.remark,
      id: form.id
    }).then(res => {
      if (res.result === 'success') {
        ElMessage.success('修改成功!')
        dialogVisible.value = false
        loadUserData()
        resolve()
      } else {
        ElMessage.error('修改失败，请检查数据是否正确!')
        reject()
      }
    }).catch(error => {
      ElMessage.error('网络请求失败，请检查网络是否畅通!')
      reject()
    })
  })
}

// 条件查询
const selectInfosByWhere = () => {
  axios.post('/user/selectByWhere.do', { name: selectUsername.value }).then(res => {
    userList.splice(0, userList.length, ...res)
  }).catch(error => {
    ElMessage.error('查询失败，请检查网络是否畅通!')
  })
}

// 添加用户
const handleAdd = () => {
  return new Promise((resolve, reject) => {
    axios.post('/user/addInfo.do', {
      name: form.username,
      pass: form.password,
      tel: form.phone,
      beizhu: form.remark
    }).then(res => {
      if (res.result === 'success') {
        ElMessage.success('保存成功!')
        dialogVisible.value = false
        loadUserData()
        resolve()
      } else {
        ElMessage.error('保存失败，请检查数据是否正确!')
        reject()
      }
    }).catch(error => {
      ElMessage.error('网络请求失败，请检查网络是否畅通!')
      reject()
    })
  })
}

// 删除用户
const handleDelete = (id) => {
  axios.post('/user/deleteInfo.do', { id }).then(res => {
    if (res.result === 'success') {
      ElMessage.success('删除成功!')
      loadUserData()
    } else {
      ElMessage.error('删除失败，请检查数据是否正确!')
    }
  }).catch(error => {
    ElMessage.error('网络请求失败，请检查网络是否畅通!')
  })
}

// 加载用户数据
const loadUserData = () => {
  axios.get('/user/getAllInfos.do').then(res => {
    userList.splice(0, userList.length, ...res)
  }).catch(error => {
    ElMessage.error('加载用户数据失败，请检查网络是否畅通!')
  })
}

// 页面加载时初始化数据
onMounted(() => {
  loadUserData()
})
</script>

<style>
.el-row {
  margin-top: 0rem;
  height: 60px;
  padding: 0cm;
  margin-bottom: 0
}
.col-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 60px;
  padding: 0px;
}
</style>
